﻿using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web.Mvc;
using db = XRM.Security.DataAccess.Models;

namespace XRM.Security.WebUI.Models.WorkKind
{
    public class WorkKindModel : BaseViewModel, IValidatableObject
    {
        public WorkKindModel()
        {
            ParamList = new List<WorkKindParamModel>();
            ParamAllList = new List<WorkKindParamModel>();
        }

        public WorkKindModel(db.WorkKind dbEntity, List<db.WorkKindParam> paramAll)
        {
            ParamList = new List<WorkKindParamModel>();
            ParamAllList = new List<WorkKindParamModel>();

            if (paramAll != null && paramAll.Any())
            {
                foreach (db.WorkKindParam item in paramAll)
                {
                    ParamAllList.Add(new WorkKindParamModel(item));
                }
            }

            if (dbEntity != null)
            {
                Id = dbEntity.WorkKindId;
                Name = dbEntity.WorkKindName;
                Description = dbEntity.Description;
                IsLinkedWithSign = dbEntity.IsLinkedWithSign;
                IsFixed = dbEntity.IsFixed;
                CustomId = dbEntity.CustomId;

                if (dbEntity.Spec != null && dbEntity.Spec.Any())
                {
                    foreach (db.WorkKindSpec item in dbEntity.Spec)
                    {
                        ParamList.Add(new WorkKindParamModel(item));
                    }
                }
            }
        }

        public void GetParamAll(List<db.WorkKindParam> paramAll)
        {
            if (paramAll != null && paramAll.Any())
            {
                foreach (db.WorkKindParam item in paramAll)
                {
                    ParamAllList.Add(new WorkKindParamModel(item));
                }
            }
        }

        [AllowHtml]
        [Display(Name = "Наименование")]
        [Required(ErrorMessage = "Поле 'Наименование' обязательное")]
        [MaxLength(200, ErrorMessage = "Максимальная длина поля 'Наименование' 200 символов")]
        public string Name { get; set; }

        [AllowHtml]
        [Display(Name = "Описание")]
        [MaxLength(500, ErrorMessage = "Максимальная длина поля 'Описание' 500 символов")]
        public string Description { get; set; }

        [Display(Name = "Связан с ЭП")]
        [Required]
        public bool IsLinkedWithSign { get; set; }
        [Required]
        public bool IsFixed { get; set; }
        public bool CanDelete { get; set; }
        public int CustomId { get; set; }

        public bool AllowParamCRUD { get; set; }
        
        [Display( Name = "Параметры" )]
        public List<WorkKindParamModel> ParamList { get; set; }

        public List<WorkKindParamModel> ParamAllList { get; set; }
        
        public void ApplyChanges(db.WorkKind dbEntity)
        {
            dbEntity.WorkKindName = Name;
            dbEntity.Description = Description;
            dbEntity.IsLinkedWithSign = IsLinkedWithSign;

            if (dbEntity.Spec != null)
                dbEntity.Spec.Clear();
            dbEntity.Spec = ParamList.Select( s => s.Id ).Select( s => new db.WorkKindSpec
                {
                    WorkKindParamId = s.Value
                } ).ToList();
        }

        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            if ( Controller.WorkKindRepository.GetAll().Any( x => x.WorkKindName == Name && x.WorkKindId != Id && !x.IsDeleted ) )
            {
                yield return new ValidationResult( "Вид работ с таким названием уже существует", new[] { "Name" } );
            }
            if (ParamList.Select(s => s.Id).Distinct().Count() != ParamList.Count)
            {
                yield return new ValidationResult( "Параметры не уникальны", new[] { "ParamList" } );
            }
        }
    }
}